package ru.minidoc.web.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import ru.minidoc.dao.ProjectDao;
import ru.minidoc.model.Project;
import ru.minidoc.model.json.ProjectData;
import ru.minidoc.model.json.ProjectList;

@Controller
public class ProjectController {
    @Autowired
    private ProjectDao projectDao;

    @RequestMapping(value = "/project/read.action", method = RequestMethod.GET)
    public @ResponseBody
    ProjectList read() {
        List<Project> projectList = projectDao.getProjectList();
        return new ProjectList(projectList.size(), projectList);
    }

    @RequestMapping(value = "/project/create.action", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Integer> create(@RequestBody ProjectData projectList) {
        Map<String, Integer> result = new HashMap<String, Integer>();
        Integer id = projectDao.create(projectList.rows);
        result.put("id", id);
        return result;
    }

    @RequestMapping(value = "/project/update.action", method = RequestMethod.POST)
    public @ResponseBody
    void update(@RequestBody ProjectData projectList) {
        projectDao.update(projectList.rows);
    }

    @RequestMapping(value = "/project/destroy.action", method = RequestMethod.POST)
    public @ResponseBody
    String destroy(@RequestBody Map<String, Integer> rows) {
        projectDao.delete(new Project(rows.get("rows")));
        return "1";
    }
}
